package com.hckjsec.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Charsets;
import com.google.common.hash.Hashing;
import com.hckjsec.common.config.FileInfoTempView;
import com.hckjsec.common.config.PartnerResultView;
import com.hckjsec.common.config.PartnerUserView;
import com.hckjsec.common.config.PartnerView;
import com.hckjsec.common.constant.Constants;
import com.hckjsec.common.core.redis.RedisCache;
import com.hckjsec.common.utils.uuid.IdUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.*;
import java.util.concurrent.TimeUnit;

//合作方人脸核身
@Component
public class DetectPartnerAuthUtil {
    @Autowired
    private RedisCache redisCache;

    public static String P_ACCESS_TOKEN_URL = "https://miniprogram-kyc.tencentcloudapi.com/api/oauth2/access_token";// 获取 Access Token
    public static String P_SIGN_TICKET_URL = "https://miniprogram-kyc.tencentcloudapi.com/api/oauth2/api_ticket";// 获取 SIGN ticket
    public static String P_ON_SEND_URL = "https://miniprogram-kyc.tencentcloudapi.com/api/server/getfaceid";// 合作方后台上送身份信息
    public static String P_ON_PULL_URL = "https://miniprogram-kyc.tencentcloudapi.com/api/server/sync";// 拉取核对信息
    /**
     * redis存储AccessToken
     */
    public static String VERIFICACATION_ACCESS_TOKEN = "verificacation_access_token:";
    /**
     * redis存储SignTicket
     */
    public static String VERIFICACATION_SIGN_TICKET = "verificacation_sign_ticket:";

    //获取AccessToken
    public  void getAccessToken(PartnerView partnerView) {
        String Access_Token= redisCache.getCacheObject(getRedisKey(partnerView.getApp_id(),"access"));
        try {
                if ("".equals(StringUtils.isHcNull(Access_Token,""))) {
                        RestTemplate restTemplate = new RestTemplate();
                        Map<String, String> params = new HashMap<>();
                        params.put("APPID", partnerView.getApp_id());
                        params.put("SECRET", partnerView.getSecret());
                        params.put("TYPE", partnerView.getGrant_type());
                        params.put("VERSION", partnerView.getVersion());
                        ResponseEntity<String> responseEntity = restTemplate.getForEntity(P_ACCESS_TOKEN_URL + "?grant_type={TYPE}&version={VERSION}&app_id={APPID}&secret={SECRET}", String.class, params);
                        String body = responseEntity.getBody();
                        JSONObject object = JSON.parseObject(body);
                        String code = object.getString("code");
                        if ("0".equals(code.trim())) {
                            Access_Token = object.getString("access_token");
                            redisCache.setCacheObject(getRedisKey(partnerView.getApp_id(), "access"), Access_Token, 18, TimeUnit.MINUTES);
                        } else {
                            partnerView.setCode("ERROR");
                        }
                }
        }catch(Exception e) {
            partnerView.setCode("ERROR");
            System.out.println("获取Access Token出错=======");
        }
        partnerView.setAccess_token(Access_Token);
    }

    //获取SignTicket
    public  void getSignTicket(PartnerView partnerView) {
        String  sign_ticket = redisCache.getCacheObject(getRedisKey(partnerView.getApp_id(),"ticket"));
        try {
            if ("".equals(StringUtils.isHcNull(sign_ticket,""))) {
                RestTemplate restTemplate = new RestTemplate();
                Map<String, String> params = new HashMap<>();
                params.put("APPID", partnerView.getApp_id());
                params.put("ACCESSTOKEN", partnerView.getAccess_token());
                params.put("VERSION", partnerView.getVersion());
                ResponseEntity<String> responseEntity = restTemplate.getForEntity(P_SIGN_TICKET_URL + "?type=SIGN&version={VERSION}&app_id={APPID}&access_token={ACCESSTOKEN}", String.class, params);
                String body = responseEntity.getBody();
                JSONObject object = JSON.parseObject(body);
                String code = object.getString("code");
                if ("0".equals(code.trim())) {
                    String tickets = object.getString("tickets");
                    JSONArray jsonArray = JSONArray.parseArray(tickets);
                    JSONObject jsonObject = jsonArray.getJSONObject(0);
                    sign_ticket = jsonObject.getString("value");
                    redisCache.setCacheObject(getRedisKey(partnerView.getApp_id(), "ticket"), sign_ticket, 55, TimeUnit.MINUTES);
                } else {
                    partnerView.setCode("ERROR");
                }
            }
        }catch(Exception e) {
            partnerView.setCode("ERROR");
            System.out.println("获取SignTicket出错=======");
        }
        partnerView.setSign_ticket(sign_ticket);
    }


    //获取NonceTicket
    public  void getNonceTicket(PartnerView partnerView) {
        String  nonce_ticket = "";
        try {
            RestTemplate restTemplate = new RestTemplate();
            Map<String, String> params = new HashMap<>();
            params.put("APPID", partnerView.getApp_id());
            params.put("ACCESSTOKEN", partnerView.getAccess_token());
            params.put("VERSION", partnerView.getVersion());
            params.put("USERID", partnerView.getUserId());
            ResponseEntity<String> responseEntity = restTemplate.getForEntity(P_SIGN_TICKET_URL+"?type=NONCE&version={VERSION}&app_id={APPID}&access_token={ACCESSTOKEN}&user_id={USERID}", String.class, params);
            String body = responseEntity.getBody();
            JSONObject object = JSON.parseObject(body);
            String code = object.getString("code");
            if ("0".equals(code.trim())) {
                String  tickets = object.getString("tickets");
                JSONArray jsonArray= JSONArray.parseArray(tickets);
                JSONObject jsonObject = jsonArray.getJSONObject(0);
                nonce_ticket = jsonObject.getString("value");
            } else {
                partnerView.setCode("ERROR");
            }
        }catch(Exception e) {
            partnerView.setCode("ERROR");
            System.out.println("获取NonceTicket出错=======");
        }
        partnerView.setUser_ticket(nonce_ticket);
    }

    //获取send
    public  void send(PartnerUserView partnerUserView,PartnerView partnerView) {
        String  faceId = "";
        try {
            String url = P_ON_SEND_URL+"?orderNo="+partnerUserView.getOrderNo();
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, partnerUserView, String.class);
            JSONObject object = JSON.parseObject(responseEntity.getBody());
            String code = object.getString("code");
            if ("0".equals(code.trim())) {
                String  result = object.getString("result");
                JSONObject jsonobject = JSON.parseObject(result);
                faceId = jsonobject.getString("faceId");
            } else {
                partnerView.setCode("ERROR");
            }
        }catch(Exception e) {
            partnerView.setCode("ERROR");
            System.out.println("获取send出错=======");
        }
        partnerView.setFaceId(faceId);
    }

    //拉取视频信息
    public PartnerResultView pull(PartnerView partnerView) {
        PartnerResultView partnerResultView = new PartnerResultView();
        try {
            RestTemplate restTemplate = new RestTemplate();
            Map<String, String> params = new HashMap<>();
            params.put("VERSION", partnerView.getVersion());
            params.put("APPID", partnerView.getApp_id());
            params.put("NONCE", partnerView.getNonce());
            params.put("ORDERNO", partnerView.getOrderNo());
            params.put("SIGN", partnerView.getSign());
            params.put("FILE", "1");
            ResponseEntity<String> responseEntity = restTemplate.getForEntity(P_ON_PULL_URL+"?version={VERSION}&app_id={APPID}&nonce={NONCE}&order_no={ORDERNO}&sign={SIGN}&get_file={FILE}", String.class, params);
            String body = responseEntity.getBody();
            JSONObject object = JSON.parseObject(body);
            partnerResultView = JSON.parseObject(JSON.toJSONString(object),PartnerResultView.class);
        }catch(Exception e) {
            System.out.println("拉取数据出错=======");
        }
        return partnerResultView;
    }




    public static String sign(List<String> values, String ticket) {
        if (values == null) {
            throw new NullPointerException("values is null");
        }
        values.removeAll(Collections.singleton(null));// remove null
        values.add(ticket);
        java.util.Collections.sort(values);
        StringBuilder sb = new StringBuilder();
        for (String s : values) {
            sb.append(s);
        }
        return Hashing.sha1().hashString(sb, Charsets.UTF_8).toString().toUpperCase();
    }


    /**
     * 设置cache key
     *
     * @param configKey 参数键
     * @return 缓存键key
     */
    public static String getRedisKey(String configKey,String type)
    {
        if ("access".equals(type)){
            return VERIFICACATION_ACCESS_TOKEN + configKey;
        }else if("ticket".equals(type)){
            return VERIFICACATION_SIGN_TICKET + configKey;
        }else{
            return VERIFICACATION_ACCESS_TOKEN + configKey;
        }
    }

    public static void main(String[] args) {

    }

}
